#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QLabel>
#include <QStatusBar>
#include <QTextStream>
#include <QTime>
#include <QMessageBox>
#include <QStringList>
#include <algorithm>
#include <QList>
#include <QPair>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{

    // 加载样式文件
    loadStyleSheet(":/styles.qss"); // 使用资源文件

    ui->setupUi(this);

    qDebug() << "Address of this (MainWindow):" << this;

    canThread = nullptr;
    canWorker= nullptr;

    tabWidget= nullptr;
    targetPage_cfg= nullptr;
    cfgpage_canset= nullptr;
    msgsendchannel= nullptr;
    canIDType= nullptr;
    candatatype= nullptr;
    combox_buardrate_channel1= nullptr;
    combox_buardrate_channel2= nullptr;
    canchannel1inhibsts= nullptr;
    canchannel2inhibsts= nullptr;
    send_candata = nullptr;
    send_canid = nullptr;
    button_opencan= nullptr;
    button_initcan= nullptr;
    button_resetcan= nullptr;
    button_startcan= nullptr;
    button_sendmsg= nullptr;
    button_cleartrace= nullptr;
    button_clearsendmsg= nullptr;
    tablewidget_trace = nullptr;







    //设置工具栏中的选项的长宽 好像没用
    //ui->toolBar->setIconSize(QSize(100, 100));

    ui->Tabwidget->setTabText(0,"IO控制");
    ui->Tabwidget->setTabText(1,"Trace");
    ui->Tabwidget->setTabText(2,"配置");

    ui->Tabwidget->setTabPosition(QTabWidget::South);


    // 创建一个标签
    QLabel *SerialLabel = new QLabel(this);
    SerialLabel->setText("   IO串口状态： ");

    QLabel *SerialConnectstatus = new QLabel(this);
    SerialConnectstatus->setText("正常");

    QLabel *CANLabel = new QLabel(this);
    CANLabel->setText("     CAN设备状态：");

    QLabel *CANConnectstatus = new QLabel(this);
    CANConnectstatus->setText("已启动");



    // 将标签添加到状态栏
    statusBar()->addPermanentWidget(SerialLabel);
    statusBar()->addPermanentWidget(SerialConnectstatus);
    statusBar()->addPermanentWidget(CANLabel);
    statusBar()->addPermanentWidget(CANConnectstatus);
    statusBar()->showMessage("测试显示效果！",3000); // 显示 3 秒




    //确定组件指针


    tabWidget =ui->centralwidget->findChild<QTabWidget*>("Tabwidget");// 通过对象名称查找



    // 获取指定索引的标签页（例如第 0 个标签页）
    targetPage_cfg = tabWidget->widget(2);

    cfgpage_canset = targetPage_cfg->findChild<QWidget*>("widget_canset");//找到can设置窗口



    msgsendchannel = cfgpage_canset->findChild<QComboBox*>("comboBox_sendchannel");
    canIDType = cfgpage_canset->findChild<QComboBox*>("comboBox_canIDType");
    candatatype = cfgpage_canset->findChild<QComboBox*>("comboBox_candatatype");

    combox_buardrate_channel1 = cfgpage_canset->findChild<QComboBox*>("combox_buardrate_channel1");
    combox_buardrate_channel2 = cfgpage_canset->findChild<QComboBox*>("combox_buardrate_channel2");
    canchannel1inhibsts = cfgpage_canset->findChild<QComboBox*>("comboBox_channel1inhibsts");
    canchannel2inhibsts = cfgpage_canset->findChild<QComboBox*>("comboBox_channel2inhibsts");
    cantraceDisplaysorType = cfgpage_canset->findChild<QComboBox*>("comboBox_tracesorttype");


    send_candata = cfgpage_canset->findChild<QLineEdit*>("lineEdit_candata");
    send_canid = cfgpage_canset->findChild<QLineEdit*>("lineEdit_canid");



    button_opencan = cfgpage_canset->findChild<QPushButton*>("pbtn_opencan");
    button_initcan = cfgpage_canset->findChild<QPushButton*>("pbtn_initcan");
    button_resetcan = cfgpage_canset->findChild<QPushButton*>("pbtn_resetcan");
    button_startcan = cfgpage_canset->findChild<QPushButton*>("pbtn_startcan");
    button_sendmsg = cfgpage_canset->findChild<QPushButton*>("pbtn_sendmsg");
    button_cleartrace = cfgpage_canset->findChild<QPushButton*>("pbtn_clearTrace");
    button_clearsendmsg = cfgpage_canset->findChild<QPushButton*>("pbtn_clearsendmsg");

    button_opencan->setStyleSheet(
        "QPushButton {"
        "   background-color: #4CAF50;"
        "   color: white;"
        "   border: none;"
        "   border-radius: 5px;"
        "   padding: 5px 10px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #45a049;"  // 悬停时的背景色
        "}"
        );

    tablewidget_trace = targetPage_cfg->findChild<QTableWidget*>("cantracewidget");



    QStringList listHeader;
    listHeader << "系统时间"  << "CAN通道"  << "ID(0x)" << "长度" << "数据(0x)"<< "传输方向" ;

    combox_buardrate_channel1->setCurrentIndex(0);
    combox_buardrate_channel2->setCurrentIndex(0);

    tablewidget_trace->setColumnCount(listHeader.count());
    tablewidget_trace->setHorizontalHeaderLabels(listHeader);

    tablewidget_trace->setColumnWidth(0,120);
    tablewidget_trace->setColumnWidth(1,120);
    tablewidget_trace->setColumnWidth(2,120);
    tablewidget_trace->setColumnWidth(3,80);
    tablewidget_trace->setColumnWidth(4,200);
    tablewidget_trace->setColumnWidth(5,120);




    tablewidget_trace->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tablewidget_trace->setSelectionBehavior(QAbstractItemView::SelectRows);


    // 创建线程和 Worker
    canThread = new QThread(this);
    canWorker = new CANThread();
    canWorker->moveToThread(canThread);


    // 连接信号与槽
    connect(canThread, &QThread::started, canWorker, &CANThread::start);
    connect(canWorker, &CANThread::destroyed, canThread, &QThread::quit);
    connect(canThread, &QThread::finished, canThread, &QObject::deleteLater);


    connect(this, &MainWindow::destroyed, canWorker, &CANThread::stop);
    connect(canWorker, &CANThread::getProtocolData, this, &MainWindow::onGetProtocolData);


    // 连接信号与槽
    //connect(button_opencan, &QPushButton::clicked, this, &MainWindow::on_pbtn_opencan_clicked);
    //connect(button_sendmsg, &QPushButton::clicked,  this, &MainWindow::on_pbtn_sendmsg_clicked);
    connect(this,&MainWindow::RequestoOpendevice,canWorker, &CANThread::openDevice );
    connect(this,&MainWindow::RequesttoClosedevice,canWorker, &CANThread::closeDevice );
    connect(this,&MainWindow::RequesttoInitdevice,canWorker, &CANThread::initCAN );
    connect(this,&MainWindow::RequesttoResetDevice,canWorker, &CANThread::reSetCAN);
    connect(this,&MainWindow::RequesttoStartDevice,canWorker, &CANThread::startCAN);
    connect(this,&MainWindow::RequesttoSendData,canWorker, &CANThread::sendData);


    connect(canWorker,&CANThread::deviceOpened ,this, &MainWindow::deviceOpensucced );
    connect(canWorker,&CANThread::deviceClosed ,this, &MainWindow::deviceCloseSucceed );
    connect(canWorker,&CANThread::deviceInited ,this, &MainWindow::deviceInitSucceed );
    connect(canWorker,&CANThread::deviceReseted ,this, &MainWindow::deviceResetSucceed );
    connect(canWorker,&CANThread::deviceStarted ,this, &MainWindow::deviceStartSucceed );
    connect(canWorker,&CANThread::senddataend ,this, &MainWindow::deviceSendDataSucced );


    connect(cantraceDisplaysorType, &QComboBox::currentIndexChanged, this, &MainWindow::on_tableWidget_sectionClicked);//报文trace界面排序

    // 启动工作线程
    canThread->start();
    //button_opencan->setText("啥啥");
    qDebug() << "MainWindow constructor completed";
    qDebug() << "CAN Thread running:" << canThread->isRunning();
    qDebug() << "CAN Worker valid:" << (canWorker != nullptr);

    qDebug() << "Address of ptn (MainWindow):" << button_opencan;
}

MainWindow::~MainWindow()
{
    delete ui;
}







// 加载样式文件
void MainWindow::loadStyleSheet(const QString &filePath) {
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream stream(&file);
        QString styleSheet = stream.readAll();
        qApp->setStyleSheet(styleSheet); // 应用样式表到整个应用程序
        file.close();
    } else {
        qWarning("Failed to open style file.");
    }
}






void MainWindow::AddDataToList(QStringList strList)
{
    // if(!ui->checkBox_4->checkState())//实时显示
    //     return;
    QString id = strList.at(2); // ID号所在列的索引是2

    if (idToRowMap.contains(id))
    {
        // 更新现有行
        int row = idToRowMap[id];
        for (int i = 0; i < strList.count(); i++)
        {
            QTableWidgetItem *item = new QTableWidgetItem(strList.at(i), 0);
            tablewidget_trace->setItem(row, i, item);
            if (i != strList.count() - 1)
                tablewidget_trace->item(row, i)->setTextAlignment(Qt::AlignCenter | Qt::AlignHCenter);
        }
    }
    else
    {
        // 新增行
        int row = tablewidget_trace->rowCount();
        tablewidget_trace->insertRow(row);
        for (int i = 0; i < strList.count(); i++)
        {
            QTableWidgetItem *item = new QTableWidgetItem(strList.at(i), 0);
            tablewidget_trace->setItem(row, i, item);
            if (i != strList.count() - 1)
                tablewidget_trace->item(row, i)->setTextAlignment(Qt::AlignCenter | Qt::AlignHCenter);
        }
        // 记录 ID 到行号的映射
        idToRowMap[id] = row;
    }


    // int row = tablewidget_trace->rowCount();
    // tablewidget_trace->insertRow(row);
    // for(int i = 0; i < strList.count();i ++)
    // {
    //     QTableWidgetItem *item = new QTableWidgetItem(strList.at(i),0);
    //     tablewidget_trace->setItem(row, i, item);
    //     if(i != strList.count() - 1)
    //         tablewidget_trace->item(row,i)->setTextAlignment(Qt::AlignCenter | Qt::AlignHCenter);

    // }
    // tablewidget_trace->scrollToBottom();
}
void MainWindow::onGetProtocolData(VCI_CAN_OBJ *vci,unsigned int dwRel,unsigned int channel)
{
    QStringList messageList;
    for(unsigned int i = 0;i < dwRel;i ++)
    {//<< "系统时间"  << "CAN通道"  << "ID号" << "长度" << "数据"<< "传输方向"
        messageList.clear();
        messageList << QTime::currentTime().toString("hh:mm:ss zzz");//时间
        messageList << "CH" + QString::number(channel);

        messageList <<  QString("%1").arg(vci[i].ID,8,16,QChar('0')).toUpper();//ID
        QString str = "";
        if(vci[i].RemoteFlag == 0)//数据帧显示数据
        {
            messageList <<  QString::number(vci[i].DataLen,16).toUpper();//长度
            for(int j = 0;j < vci[i].DataLen;j ++)
                str = QString("%1 ").arg(vci[i].Data[j],2,16,QChar('0')).toUpper();//QString::number(recvCANData[i].frame.data[j],16) + " ";
        }
        else
            messageList << "0";//长度
        messageList << str;//数据
        messageList << "接收";//收发
        AddDataToList(messageList);
    }
}

QString versionStr(USHORT ver)
{
    return "V" + QString::number((ver & 0x0FFF) /0x100,16).toUpper() + "." + QString("%1 ").arg((ver & 0x0FFF) % 0x100,2,16,QChar('0')).toUpper();
}

void MainWindow::onBoardInfo(VCI_BOARD_INFO vbi)
{
    ui->label_9->setText(QString::number(vbi.can_Num));
    ui->label_10->setText(versionStr(vbi.hw_Version));
    ui->label_12->setText(versionStr(vbi.in_Version));
    ui->label_13->setText(QString::number(vbi.irq_Num));
}

void MainWindow::on_pbtn_opencan_clicked()//打开
{

    if (!this->button_opencan) {
        qDebug() << "Error: button_opencan is nullptr!";
        return;
    }

    if(this->button_opencan->text() == tr("打开设备"))
    {
        qDebug()<<"ceshi1";
        UINT baundRate = 0;
        baundRate = combox_buardrate_channel1->currentText().toUInt();
        emit RequestoOpendevice(4,0, baundRate);

    }
    else if(this->button_opencan->text() == tr("关闭设备"))
    {
        qDebug()<<"ceshi2";
        emit RequesttoClosedevice();
    }

    qDebug()<<"ceshi6";
}


void MainWindow::on_pbtn_sendmsg_clicked()
{
    if(canIDType->currentIndex() == 0)//标准帧，ID 范围0-0x7FF
    {
        if(send_candata->text().toInt(Q_NULLPTR,16) > 0x7FF)
        {
            QMessageBox::warning(this,"警告","发送失败，标准帧ID范围为0~0x7FF！");
            return;
        }
    }
    else
    {
        if(send_candata->text().toInt(Q_NULLPTR,16) > 0x1FFFFFFF)
        {
            QMessageBox::warning(this,"警告","发送失败，扩展帧ID范围为0~0x1FFFFFFF！");
            return;
        }
    }
    QStringList strList = send_candata->text().split(" ");
    unsigned char data[8];
    memset(data,0,8);
    UINT dlc = 0;
    dlc = strList.count() > 8 ? 8 : strList.count();
    for(int i = 0;i < dlc;i ++)
        data[i] = strList.at(i).toInt(Q_NULLPTR,16);

    emit  RequesttoSendData(QVariant(msgsendchannel->currentIndex()).toUInt(),
                           QVariant(send_canid->text().toInt(Q_NULLPTR,16)).toUInt(),
                           candatatype->currentIndex(),
                           canIDType->currentIndex(),
                           data,dlc);

}

void MainWindow::on_pbtn_clearTrace_clicked()
{
    tablewidget_trace->setRowCount(0);
    idToRowMap.clear();
}

void MainWindow::on_pbtn_resetcan_clicked()//复位
{
    emit RequesttoResetDevice();

}

void MainWindow::on_pbtn_initcan_clicked()//初始化
{
    emit RequesttoInitdevice();

}

void MainWindow::on_pbtn_startcan_clicked()//启动
{
    emit RequesttoStartDevice();


}

void MainWindow::deviceOpensucced(bool state)
{
    if(state == true)
    {
        button_opencan->setEnabled(true);
        button_initcan->setEnabled(true);
        button_startcan->setEnabled(false);
        button_resetcan->setEnabled(false);
        combox_buardrate_channel1->setEnabled(false);
        button_opencan->setText(tr("关闭设备"));
    }
    else
        QMessageBox::warning(this,"警告","打开设备失败！");
}

void MainWindow::deviceCloseSucceed(bool state)
{
    if(state == true){
        button_opencan->setEnabled(true);
        button_initcan->setEnabled(false);
        button_startcan->setEnabled(false);
        button_resetcan->setEnabled(false);
        combox_buardrate_channel1->setEnabled(true);
        msgsendchannel->setEnabled(true);
        button_sendmsg->setEnabled(false);

        button_opencan->setText(tr("打开设备"));
        QMessageBox::warning(this,"警告","设备关闭！");
    }
    else
        QMessageBox::warning(this,"警告","设备未关闭成功！");
}

void MainWindow::deviceInitSucceed()
{
    button_opencan->setEnabled(true);
    button_startcan->setEnabled(true);
    button_initcan->setEnabled(true);
    button_startcan->setEnabled(true);
    button_resetcan->setEnabled(false);
}

void MainWindow::deviceResetSucceed()
{
    qDebug()<< "ceshifuwei";
    button_opencan->setEnabled(true);
    button_initcan->setEnabled(false);
    button_startcan->setEnabled(true);
    button_resetcan->setEnabled(false);
    button_sendmsg->setEnabled(false);

}

void MainWindow::deviceStartSucceed()
{
    button_opencan->setEnabled(true);
    button_initcan->setEnabled(false);
    button_startcan->setEnabled(false);
    button_resetcan->setEnabled(true);
    button_sendmsg->setEnabled(true);
}

void MainWindow::deviceSendDataSucced()
{

    QStringList messageList;
    //<< "系统时间"  << "CAN通道"  << "ID号" << "长度" << "数据"<< "传输方向"
    messageList.clear();
    messageList << QTime::currentTime().toString("hh:mm:ss zzz");//时间
    messageList << QString::number(QVariant(msgsendchannel->currentIndex()).toUInt());

    messageList << send_canid->text().toUpper();//ID
    QString str = "";
    QString candata_strList = send_candata->text();
    QStringList strList = send_candata->text().split(" ");

    UINT dlc = strList.count() > 8 ? 8 : strList.count();

    messageList <<  QString::number(dlc,16).toUpper();//长度

    messageList << candata_strList;//数据
    messageList << "发送";//收发
    AddDataToList(messageList);


}

void MainWindow::debugmsg()
{
    qDebug()<< "当前页是" ;
}




// 实现 on_tableWidget_sectionClicked
void MainWindow::on_tableWidget_sectionClicked(int logicalIndex)
{
    qDebug()<< "收到报文";
    if (logicalIndex == 1) // ID 列的索引是 2
    {
        on_sortByID_clicked();
    }
}



void MainWindow::on_sortByID_clicked()
{
    // 1. 收集所有行的数据
    QList<QPair<QString, QStringList>> rowsData;
    for (int row = 0; row < tablewidget_trace->rowCount(); ++row)
    {
        QStringList rowData;
        for (int col = 0; col < tablewidget_trace->columnCount(); ++col)
        {
            QTableWidgetItem *item = tablewidget_trace->item(row, col);
            rowData << (item ? item->text() : "");
        }
        QString id = rowData.at(2); // ID 列的索引是 2
        rowsData.append(QPair<QString, QStringList>(id, rowData));
    }

    // 2. 按 ID 排序
    std::sort(rowsData.begin(), rowsData.end(),
              [](const QPair<QString, QStringList> &a, const QPair<QString, QStringList> &b) {
                  return a.first < b.first; // 升序排序
              });

    // 3. 清空表格和映射
    tablewidget_trace->setRowCount(0);
    idToRowMap.clear();

    // 4. 重新填充表格和映射
    for (const auto &rowData : rowsData)
    {
        int newRow = tablewidget_trace->rowCount();
        tablewidget_trace->insertRow(newRow);
        for (int col = 0; col < rowData.second.count(); ++col)
        {
            QTableWidgetItem *item = new QTableWidgetItem(rowData.second.at(col));
            tablewidget_trace->setItem(newRow, col, item);
            if (col != rowData.second.count() - 1)
                tablewidget_trace->item(newRow, col)->setTextAlignment(Qt::AlignCenter | Qt::AlignHCenter);
        }
        // 更新映射
        idToRowMap[rowData.first] = newRow;
    }
}

